/**
 * Custom non marionette views used to render non hierarchical structures
 * 
 * Here we render the html snippets for the different products/work/work_item
 * elements that are rendered in tbody s
 * 
 */
import Radio from 'backbone.radio';


const PRODUCT_VIEW_TEMPLATE = require('./templates/ProductRawView.mustache');
const WORK_VIEW_TEMPLATE = require('./templates/WorkRawView.mustache');
const WORK_ITEM_VIEW_TEMPLATE = require('./templates/WorkItemRawView.mustache');


/**
 * 
 * @param {BaseProductModel} model 
 * @param {integer} index 
 * @returns Template variables related to the Product 
 */
const _baseProductContext = (model, index) => {
    const ctx = Object.assign({}, model.attributes);
    const user_prefs = Radio.channel("user_preferences");
    for (const key of ['total_ht_to_invoice', 'total_tva_to_invoice', 'total_ttc_to_invoice', 'total_ht', 'tva_amount', 'total_ttc']) {
        ctx[key] = user_prefs.request('formatAmount', model.get(key), true);
    }
    for (const key of ['already_invoiced', 'percentage']) {
        ctx[key] = model.get(key) || 0;
    }
    if (!model.get('percent_left') && !model.get('percent_left') == 0) {
        ctx['percent_left'] = 100;
    }

    ctx["htmlIndex"] = index;
    return ctx
}
/**
 * 
 * @param {ProductCollection} collection 
 * @returns The representation of the collection as a serie of tbodys
 */
export const getProductCollectionHtml = function (collection) {
    let result = "";
    collection.each(
        (model, index) => {
            if (model.get('type_') == 'progress_invoicing_work') {
                result += getWorkViewHtml(model, index);
            } else {
                result += getProductViewHtml(model, index);
            }
        }
    )
    return result;
}
/**
 * 
 * @param {ProductModel} model 
 * @param {number} index 
 * @returns The html representation of this product model
 */
export const getProductViewHtml = function (model, index) {
    const ctx = _baseProductContext(model, index);
    return PRODUCT_VIEW_TEMPLATE(ctx);
}
/**
 * 
 * @param {WorkModel} model 
 * @param {number} index 
 * @returns An html representation of the model and its items
 */
export const getWorkViewHtml = function (model, index) {
    let itemsRawHtml = '';
    model.items.each(
        (item, index) => {
            itemsRawHtml += getWorkItemViewHtml(item, index, model);
        }
    )
    let ctx = _baseProductContext(model, index);
    ctx["workitemsHtml"] = itemsRawHtml;
    ctx['locked'] = model.get('locked')

    return WORK_VIEW_TEMPLATE(ctx);
}
/**
 * 
 * @param {WorkItemModel} model 
 * @param {number} index 
 * @returns A html representation of the WorkItemModel
 */
export const getWorkItemViewHtml = function (model, index, work) {
    let ctx = _baseProductContext(model, index);
    ctx['locked'] = work.get('locked');
    return WORK_ITEM_VIEW_TEMPLATE(ctx);
}